import asyncio  
  
class SimpleRedisServer:  
    def __init__(self, host='127.0.0.1', port=16379):  
        self.host = host  
        self.port = port  
        self.db = {}  
  
    async def handle_client(self, reader, writer):  
        address = writer.get_extra_info('peername')  
        print(f"New connection from {address}")  
  
        try:  
            while True:  
                # 读取直到遇到行结束符或读取了最多100个字节  
                data = await reader.readuntil(b'\n')
  
                # 移除行结束符  
                data = data.strip()  
  
                # 简单解析命令，只处理SET和GET  
                command, *args = data.decode().split()  
                print(command)  
                if command == 'SET':  
                    key, value = args  
                    self.db[key] = value  
                    response = b'OK\n'  
                elif command == 'GET':  
                    key = args[0]  
                    response = (self.db.get(key, 'nil') + '\n').encode()  
                else:  
                    response = b'ERR unknown command\n'  
  
                writer.write(response)  
                await writer.drain()    
  
        except ConnectionResetError:  
            print('Client disconnected')  
        finally:  
            writer.close()  
  
    async def start_server(self):  
        server = await asyncio.start_server(  
            self.handle_client, self.host, self.port)  
  
        addr = server.sockets[0].getsockname()  
        print(f'Serving on {addr}')  
  
        async with server:  
            await server.serve_forever()  
  
if __name__ == '__main__':  
    server = SimpleRedisServer()  
    asyncio.run(server.start_server())